from urllib.parse import urlencode

import requests
import re
import os
from bs4 import BeautifulSoup

#######全局相关配置 #######

mainBaseUrl = "http://jszx-jxpt.cuit.edu.cn"
baseworkListUrl = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/"
daily_signUrl1 = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/sj.asp?UTp=Xs&jkdk=Y"
submitType1Url = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/editSjRs.asp"
mainUrl = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/sj.asp?UTp=Xs&jkdk=N"  #must
mustUrl1 = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/sjDb.asp?UTp=Xs&jkdk=N&ObjId="  #must
mustUrlJkdk = "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/sjDb.asp?UTp=Xs&jkdk=Y&ObjId="  #must
mustUrl2 = "http://jszx-jxpt.cuit.edu.cn/jxgl/share/ChkLgn.asp?txtId="  #must
BaseFileUploadUrl = "http://jszx-jxpt.cuit.edu.cn/jxgl/share/UploadJob.asp?a=upload&Type=Js&ID="
tmpfileSavepath = "D:\\XiaoRan-Spider\\"
workNameList = {}
workLinkList = {}
type1Data = {} #程序跟踪调试数据
cookieA = requests.cookies.RequestsCookieJar() #被复制的同学的cookie
defaultUsername = '2020081061'  #配置默认账号
defaultPassword = ''  #配置，默认密码
usernameA = ''
usernameB = ''
cookieB = requests.cookies.RequestsCookieJar() #复制到的同学的cookie
proxies = {
        "http": "http://127.0.0.1:8888",
        "https": "http://127.0.0.1:8888",
    }
fileList = []
#这里为了方便fiddler调试
sessionA = requests.session()
sessionB = requests.session()
submitType1Headers={
    "Host": "jszx-jxpt.cuit.edu.cn",
    "Connection": "keep-alive",
    "Origin": "http://jszx-jxpt.cuit.edu.cn",
    "Content-Type": "application/x-www-form-urlencoded;charset=gb2312",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Referer": "http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netKs/editSj.asp"
}

#######全局相关配置 #######

def login(username, password, session):
    url = 'http://login.cuit.edu.cn/Login/xLogin/Login.asp'
    data = {
        'txtId': username,
        'txtMM': password,
        'verifycode': '%B2%BB%B7%D6%B4%F3%D0%A1%D0%B4',
        'codeKey': '480980',
        'Login': 'Check',
        'IbtnEnter.x': 42,
        'IbtnEnter.y': 4
    }

    headers = {
        'Host': 'login.cuit.edu.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': '150',
        'Origin': 'http://login.cuit.edu.cn',
        'Connection': 'close',
        'Referer': 'http://login.cuit.edu.cn/Login/xLogin/Login.asp',
        'Upgrade-Insecure-Requests': '1',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache'
    }
    # session = requests.session()
    req = session.post(url=url, data=data, headers=headers, allow_redirects=False)
    cookiejar1 = requests.cookies.RequestsCookieJar()
    for cookie in req.cookies:
        cookiejar1.set(cookie.name, cookie.value)

    for cookie in req.headers['Set-Cookie'].split(";"):
        key = cookie.split('=')[0]
        value = cookie.split('=')[1]
        cookiejar1.set(key, value)

    headers2 = {
        'Host': 'jszx-jxpt.cuit.edu.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Cookie': '123',
        'Connection': 'close',
        'Upgrade-Insecure-Requests': '1'
    }
    req2 = session.get(url='http://jszx-jxpt.cuit.edu.cn/jxgl/xs/netks/sj.asp?jkdk=Y', headers=headers2, allow_redirects=False)

    cookiejar2 = requests.cookies.RequestsCookieJar()
    for cookie in req2.cookies:
        cookiejar2.set(cookie.name, cookie.value)

    for cookie in req2.headers['Set-Cookie'].split(";"):
        key = cookie.split('=')[0]
        value = cookie.split('=')[1]
        cookiejar2.set(key, value)

    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/UserPub/Login.asp?UTp=Xs', cookies=cookiejar2, allow_redirects=False)
    req = session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/Login/tyLogin.asp', cookies=cookiejar2, allow_redirects=False)
    html = req.text
    dircUrl = re.search('URL=(.*?)">', html).group(1)
    session.get(url=dircUrl, cookies=cookiejar1, allow_redirects=False)
    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/Login/tyLogin.asp', cookies=cookiejar1, allow_redirects=False)
    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/Login/syLogin.asp', cookies=cookiejar1, allow_redirects=False)
    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/UserPub/Login.asp?UTp=Xs&Func=Login', cookies=cookiejar1, allow_redirects=False)
    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/MainMenu.asp', cookies=cookiejar1, allow_redirects=False)
    session.get(url='http://jszx-jxpt.cuit.edu.cn/Jxgl/Xs/netks/sj.asp', cookies=cookiejar1, allow_redirects=False)

def type1(url):
    print("type1")
    print(url)
    global cookieB
    content = sessionA.get(url)
    sessionB.get(url)
    content.encoding="gb2312"
    content = BeautifulSoup(content.text, "lxml")
    inputs = content.find_all("input")
    data={}
    for info in inputs:
        input_name = info["name"]
        if(str(info).find("value") > 0):
            input_val = info["value"]
            tmpname = "aa"+info["name"]
            #这里这个处理非常难堪。debug试了很久，这个name的值有问题
            if(tmpname.find("wtOR") > 0):
                input_val = '1'
        else:
            input_val = ''
        data[input_name]=input_val
    data["ObjId"] = usernameB
    #换username
    data = urlencode(data, encoding="gb2312")
    print(data)
    res = sessionB.post(submitType1Url, data=data, headers=submitType1Headers)
    res.encoding="gb2312"
    print(res.text)
    print()
    print("\t未报错则全部操作成功，xiaoran暂未提供检测功能，请自行登录计算中心判断是否完成数据拷贝")

def type2(url):
    print("到此")
    id = url.split("&Id=")[1]
    getAllFile(url)
    uploadUrl = BaseFileUploadUrl + "jK%5F1001%5F"+ id +"%7CXs%5F"+usernameB
    fileP = tmpfileSavepath + str(id) + "\\"
    fileLi = os.listdir(fileP)
    for fileIn in fileLi:
        openFilePath = fileP + fileIn
        files = []
        files.append(("file1", (fileIn, open(openFilePath, "rb"), "application/octet-stream")))
        res = sessionB.post(uploadUrl, files=files)
        res.encoding = "gb2312"
    print()
    print()
    print("未报错则全部操作成功，xiaoran暂未提供检测功能，请自行登录计算中心判断是否完成数据拷贝")

def getAllFile(url):
    #从user1保存文件
    res = sessionA.get(url)
    id = url.split("&Id=")[1]
    res.encoding = "gb2312"
    content = res.text
    alist = BeautifulSoup(content, "lxml").find_all("a")
    print(alist)
    global UploadcheckUrl
    for ainfo in alist:
        if(ainfo["href"].find("ChkLgn") > 0):
            UploadcheckUrl = mainBaseUrl + ainfo["href"]
            break
    res = sessionA.get(UploadcheckUrl)
    res.encoding = "gb2312"
    soup = BeautifulSoup(res.text, "lxml").find_all("a")
    global fileList
    for ali in soup:
        if(ali["href"].find("&a=dl&f=") > 0):
            fileList.append(mainBaseUrl + "/jxgl/share/" + ali["href"])
    #文件保存
    global tmpfileSavepath
    mkdir(tmpfileSavepath)
    fileSaveP = tmpfileSavepath + str(id)
    mkdir(fileSaveP)
    for durl in fileList:
        fileName = durl.split("&a=dl&f=")[1].split("%5F")[1].replace("%2E", ".")
        ioFile = sessionA.get(durl)
        with open(fileSaveP + "\\" + fileName, "wb+") as f:
            f.write(ioFile.content)

def getworkDetail(url):
    res = sessionA.get(url)
    res.encoding = "gbk"
    soup = BeautifulSoup(res.text, "lxml")
    clist = soup.find_all("a")
    print(clist)
    for alist in clist:
        alink = baseworkListUrl + alist["href"]
        # print(alink)
        # print(alist["href"])
        if(alink.find("editSj") > 0):
            alist = "xiaoran666"+alist.text
            print(alist)
            if(alist.find("程序跟踪调试") > 0):
                type1(alink)
            else:
                type2(alink)
                #文件上传为一种类型

def jszx():
    print()
    print()
    print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+")
    print()
    print("\t<--程序开始运行-->")
    print("\t\t\t<--无法及时完成作业？不可能！-->")
    print("\t\t\t<--XiaoRan为你保驾护航-->")
    print("\t\t\t<--此脚本仅供江湖救急-->")
    print("\t=== 希望大家可以认认真真做完每一道题，认真思考每一个算法逻辑 ===")
    print()
    print("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+")
    print()
    print("\t== 请输入已完成作业的同学的学号密码 ==")
    print("\t== 学号输入0选择指定的默认账号 ==")
    global usernameA
    usernameA = input("--> 请输入对方学号：")
    if(int(usernameA) == 0):
        usernameA = defaultUsername
        passwordA = defaultPassword
    else:
        passwordA = input("--> 请输入对方密码：")
    global cookieA
    global cookieB
    login(usernameA, passwordA, sessionA)
    print("\t== 请输入复制到的学号密码 ==")
    global usernameB
    usernameB = input("--> 请输入你的学号：")
    passwordB = input("--> 请输入你的密码：")
    login(usernameB, passwordB, sessionB)
    sessionA.get(mainUrl)
    sessionB.get(mainUrl)
    #接下来拿到被复制的账号的数据
    chooseList()

def chooseList():
    response = sessionA.request("GET", mainUrl)
    response.encoding = "gbk"
    content = BeautifulSoup(response.text, "lxml")
    arlist = content.find_all(name="tr",bgcolor="#E0E8FF")

    i=1
    for list in arlist:
        for alist in list.find_all(name="a", target="_self"):
            workNameList[i] = alist.text
            workLinkList[i] = baseworkListUrl + alist["href"]
            i=i+1
    print()
    print()
    print("--> 请选择要完成的作业")
    j=1
    for ptval in workNameList.values():
        print("\t%d. %s"%(j, ptval))
        j=j+1
    print("\t0. 以上全部")
    print()
    userInput = input("--> 请输入对应序号：")
    print(userInput)
    url = workLinkList[int(userInput)]
    print(url)
    #must
    sessionB.get(url.replace(str(usernameA), str(usernameB)))
    id = url.split("&Id=")[1]
    sessionA.get(mustUrl2+"jK_1001_"+str(id)+"|Xs_"+str(usernameA))
    sessionB.get(mustUrl2+"jK_1001_"+str(id)+"|Xs_"+str(usernameB))
    #选择适当的函数处理
    getworkDetail(url)


def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return True
    else:
        return False

def dailySign():
    username = input("输入学号：")
    password = input("输入密码：")
    session = requests.session()
    login(username, password, session)
    isOut = input("是否有出校的需求？1->有、0->无 :")
    res = session.get(daily_signUrl1)
    res.encoding = "gb2312"
    soup = BeautifulSoup(res.text, "lxml")
    link = soup.find(name="tr", bgcolor="#E0E8FF")
    td = link.find_all("td")[1]
    print(td)
    aurl = td.find("a")["href"]
    id = aurl.split("&Id=")[1]
    mustUrl = baseworkListUrl + aurl
    mainSign = session.get(mustUrl)
    mainSign.encoding="gb2312"
    sign_data={
    "B1":"%CC%E1%BD%BB%B4%F2%BF%A8",
    "RsNum":"3",
    "Id":"13085",
    "Tx":"33_1",
    "canTj":"1",
    "isNeedAns":"0",
    "UTp":"Xs",
    "ObjId":"2020081061",
    "th_1":"21650",
    "wtOR_1":"1",
    "sF21650_1":"1",
    "sF21650_2":"",
    "sF21650_3":"",
    "sF21650_4":"",
    "sF21650_5":"1",
    "sF21650_6":"1",
    "sF21650_7":"1",
    "sF21650_8":"1",
    "sF21650_9":"1",
    "sF21650_10":"",
    "sF21650_N":"10",
    "th_2":"21912",
    "wtOR_2":"",
    "sF21912_1":"",  #目的地
    "sF21912_2":"",  #是由
    "sF21912_3":"",
    "sF21912_4":"",
    "sF21912_5":"",
    "sF21912_6":"",
    "sF21912_N":"6",
    "th_3":"21648",
    "wtOR_3":"N%5C%7C%2F%5C%7C%2FN%5C%7C%2F%5C%7C%2FN%5C%7C%2F",
    "sF21648_1":"N",
    "sF21648_2":"",
    "sF21648_3":"N",
    "sF21648_4":"",
    "sF21648_5":"N",
    "sF21648_6":"",
    "sF21648_N":"6",
    "zw1":"",
    "cxStYt":"A",
    "zw2":""
}
    if(int(isOut) == 1):
        sign_data["wtOR_2"] = ""
        sign_data["sF21912_1"] = "校外"
        sign_data["sF21912_2"] = "剪头发。"
        sign_data["sF21912_3"] = "1"
        sign_data["sF21912_4"] = "06"
        sign_data["sF21912_5"] = "1"
        sign_data["sF21912_6"] = "23"
    sign_data["Id"] = id
    sign_data["ObjId"] = username
    sign_data = urlencode(sign_data, encoding="gb2312")
    res = session.post(submitType1Url, data=sign_data, headers=submitType1Headers, proxies = proxies)
    res.encoding = "gb2312"
    print("未报错则全部操作成功，xiaoran暂未提供检测功能，请自行登录计算中心判断是否完成数据拷贝")

def menu():
    print("\t<<< 脚本作者：XiaoRan >>>")
    print("\t<<< 声明：脚本免费使用且仅供学习参考，请勿用作其他用途。")
    print("--> 请输入功能对应的序号：")
    print("\t === 0. 计算中心作业数据拷贝 ===")
    print("\t === 1. 每日健康打卡 ===")
    userI = input("\t请输入指令：")
    if(int(userI) == 1):
        dailySign()
    if(int(userI) == 0):
        jszx()
    print()
    print()
    print("\t《《《 脚本已开始执行开始 》》》")

if __name__ == "__main__":

    menu()

